<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">

      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.jobNumber"
            style="width: 150px;margin-right:15px;"
            class="filter-item"
            placeholder="请输入员工工号"
      ></el-input>

      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.departmentName"
            style="width: 180px;margin-right:15px;"
            class="filter-item"
            placeholder="请输入车间"
      ></el-input>

      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.sectionNo"
            style="width: 180px;margin-right:15px;"
            class="filter-item"
            placeholder="请输入工段号"
      ></el-input>

      <el-date-picker
        clearable
        v-model="listQuery.createTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        placeholder="开始时间"
        type="datetime"
        style="width: 180px;margin-right:15px;" class="filter-item"
      >
      </el-date-picker>
      <el-date-picker
        clearable
        v-model="listQuery.finishTime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="结束时间"
        type="datetime"
        style="width: 180px;margin-right:15px;" class="filter-item"
      ></el-date-picker>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>

    </div>
    
    <!-- table 表格 -->
    <el-table :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column  label="员工工号"  prop="jobNumber" align="center"/>
      <el-table-column  label="员工姓名"  prop="userName" align="center"/>
      <el-table-column  label="工段"  prop="sectionNo" align="center"/>
      <el-table-column  label="车间"  prop="departmentName" align="center"/>
      <el-table-column  label="原质量系数" prop='initial' align="center"/>
      <el-table-column  label="扣罚系数" prop='nature_coefficient' align="center"/>
      <!-- <el-table-column  label="扣罚原因" align="center">
        <template slot-scope="scope">
            <div 
              v-for="(item,index) in scope.row.issueList" 
              :key='index'>
              {{index+1}}{{'.' + item.issueLittle}}
            </div>
        </template>
      </el-table-column> -->
      <el-table-column  label="最终质量系数" prop='ultimately' align="center"/>
      <!-- 对员工数据进行编辑与删除操作 -->
      <el-table-column  label="扣罚详情" align="center">
        <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="details(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
   
      <!-- 当月品质奖惩记录 -->
    <el-dialog title="当月扣罚记录" :visible.sync="dialogFormVisible" width="700px">
      <div v-infinite-scroll="load" class="records">
        <el-form ref="modifyform" :model="modifyform" label-width="120px" size="medium">
          <div v-for="(item,index) in modifyform" :key="index">
          <el-divider content-position="left">问题索引：{{item.issueIndexes}}</el-divider>
          <el-form-item label="扣罚原因">
            <el-input v-model="item.disqualificationDesc" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="设备条码">
            <el-input v-model="item.deviceBarcode" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="问题小类">
            <el-input v-model="item.issueLittle" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="问题大类">
            <el-input v-model="item.issueLarge" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="责任环节">
            <el-input v-model="item.responsibility" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="问题性质">
            <el-input v-model="item.natureName" style="width:300px" :disabled="true" />
          </el-form-item>
          <el-form-item label="扣罚系数">
            <el-input v-model="item.natureCoefficient" style="width:300px" :disabled="true" />
            <!-- <div>{{modifyform.natureCoefficient}}</div> -->
          </el-form-item>
          </div>
        </el-form>
      </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

     <el-divider></el-divider>

    <el-button type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { findUserQualityScore } from '@/api/performance.js'
import {obj_is_null,throttle } from '@/utils/publicFun'
export default {
    name: 'massCoefficientDetail',
    data() {
        return {
            total: 0,                           //数据的总数
            listQuery: {
                jobNumber: '',
                departmentName: '',
                sectionNo: '',
                createTime: '',
                finishTime: '',
                page: 1,
                limit: 10,
            },
            tableInfo: [],
            loadingList: false,
            loading: false,
            dialogFormVisible: false,
            tableList: [],
            modifyform: {}
        }
    },
    methods: {
    transformDat(res) {
      const mapInfo = {
        userName: '员工姓名',
        jobNumber: '员工工号',
        sectionNo: '工段',
        departmentName: '车间',
        initial: '原质量系数',
        nature_coefficient: '扣罚系数',
        ultimately: '最终质量系数'
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      const data = res.map(obj => Object.values(obj))
      console.log(data)
      return { header, data }
    },
    // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      query.createTime = query.createTime == null ? '' : query.createTime
      query.finishTime = query.finishTime == null ? '' : query.finishTime
      if(query.createTime) {
        if(!query.finishTime) return this.$message({
                message: '请选择结束时间',
                type: 'warning'
            })
      } else {
        if (query.finishTime) return this.$message({
                message: '请选择开始时间',
                type: 'warning'
            })
      }
      query.page = 1
      query.limit = 10000
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)

      let arr = await findUserQualityScore(query)
      arr.data.list.forEach(item => {
          item.initial = 1
          item.sectionNo = item.sectionNo == 'null'?'':item.sectionNo
      });
      // 计算扣罚系数
      arr.data.list.forEach(item => {
          item.nature_coefficient = 0
          let nature_coefficient1 = 0
          item.disqualificationViewList.forEach(items => {
            if(items.natureCoefficient) {
              nature_coefficient1 += parseFloat(items.natureCoefficient)
            }
          });
          nature_coefficient1 = String(nature_coefficient1).replace(/^(.*\..{4}).*$/,"$1")
          item.nature_coefficient = Number(nature_coefficient1)
      });
      // 计算最终质量系数
      arr.data.list.forEach(item => {
          item.ultimately = 1 - item.nature_coefficient
      });
      arr.data.list.forEach(item => {
          delete item.disqualificationList
          delete item.disqualificationViewList
      });
      let nameString = query.departmentName?query.departmentName + '-':''
      let jobNumberString = query.jobNumber?'工号' + query.jobNumber + '-':''
      let sectionNoString = query.sectionNo?'工段号' + query.sectionNo + '-':''
      let createTimeString = query.createTime?'开始时间' + query.createTime + '-':''
      let finishTimeString = query.finishTime?'结束时间' + query.finishTime + '-':''
      let nameLengthen = nameString + jobNumberString + sectionNoString + createTimeString + finishTimeString
      const { header, data } = this.transformDat(arr.data.list)
        import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: nameLengthen + '员工质量系数excel', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
    // 搜索按钮绑定的函数，向服务器发送表单数据
    // 所有传输的表单字段都不是必须的，按需查询
    async handleFilter() {
      let query = Object.assign({},this.listQuery)
      // 开始时间以及结束时间必须同时选择或者同时不选择
      query.createTime = query.createTime == null ? '' : query.createTime
      query.finishTime = query.finishTime == null ? '' : query.finishTime
      if(query.createTime) {
        if(!query.finishTime) return this.$message({
                message: '请选择结束时间',
                type: 'warning'
            })
      } else {
        if (query.finishTime) return this.$message({
                message: '请选择开始时间',
                type: 'warning'
            })
      }
      this.loadingList = true
      let {data} = await findUserQualityScore(query)
      this.tableInfo = data.list==null?[]:data.list
      this.tableInfo.forEach(item => {
          item.initial = 1
          item.sectionNo = item.sectionNo == 'null'?'':item.sectionNo
      });
      // 计算扣罚系数
      this.tableInfo.forEach(item => {
          item.nature_coefficient = 0
          let nature_coefficient1 = 0
          item.disqualificationViewList.forEach(items => {
            if(items.natureCoefficient) {
              nature_coefficient1 += parseFloat(items.natureCoefficient)
            }
          });
          nature_coefficient1 = String(nature_coefficient1).replace(/^(.*\..{4}).*$/,"$1")
          item.nature_coefficient = Number(nature_coefficient1)
      });
      // 计算最终质量系数
      this.tableInfo.forEach(item => {
          item.ultimately = 1 - item.nature_coefficient
      });
      this.total = data.totle
      this.loadingList = false
    },
    // 查看详情的按钮绑定的函数，将数据传递到目标弹窗
    // item为对应的整行数据
    details(item) {
      if (!item.disqualificationViewList.length || !item.disqualificationViewList[0].natureCoefficient) return this.$confirm('该员工暂无扣罚记录', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      this.dialogFormVisible = true
      this.modifyform = item.disqualificationViewList
    },
    // table表单下方的页码组件改变每页显示的数据条数
     handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
    // table表单下方的页码组件改变页面
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    },
    getData() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.handleFilter()
    },
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter()
  }
}
</script>

<style>
.records{
  overflow:auto;
  max-height: 500px;
  padding: 20px;
}
</style>